package com.freework.queryData.compileSQL.simpleSQL;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.freework.queryData.compileSQL.CompileSQL;
import com.freework.queryData.compileSQL.SqlAndParam;

public class SimpleCmpleSQL implements CompileSQL {

	private String sourceSql="";
	private List<ISQLPart> sqlParts=null;
	private SQLPartAnalyze analyze;
	
	public void setAnalyze(SQLPartAnalyze analyze) {
		this.analyze = analyze;
	}
	public List<ISQLPart> getSqlParts() {
		return new ArrayList<ISQLPart>(sqlParts);
	}
	public SimpleCmpleSQL(){}
	public SimpleCmpleSQL(String sourceSql,SQLPartAnalyze analyze){
		this.analyze=analyze;
		this.setSourceSql(sourceSql);
	}
	public void setSourceSql(String sourceSql) {
		this.sourceSql = sourceSql;
		analyze(sourceSql);
		
	}
	private void analyze(String sourceSql){
		//System.out.println(sourceSql);
		if(analyze==null)
		   analyze=new SQLPartAnalyze();
		sqlParts=analyze.analyze(sourceSql);
		
	}
	@Override
	public Set<String> getParamNames() {
		HashSet<String> set=new HashSet<String>();
		for (ISQLPart sqlPart : sqlParts) {
			if(sqlPart.getParamNames()!=null)
				set.addAll(sqlPart.getParamNames());
		}
		
		return set;
	}

	@Override
	public String getSourceSql() {
		return sourceSql;
	}

	@Override
	public SqlAndParam getSQL(Object param) {
		
		List<Object> list=new LinkedList<Object>();
		//String targetSql=sourceSql;
		StringBuilder targetSql=new StringBuilder(sqlParts.size()*10);
		for (ISQLPart sqlPart : sqlParts) {
			sqlPart.addSqlAndParam(param, list, targetSql);
		}

		return new SqlAndParam(targetSql.toString(),list);
	}

public  static void main(String ra[]){
		
		 String sql="select FUNCID, FUNCNAME, ( select count(*) from  SYS_FUNC my_tmp where my_tmp.PFUNCID=t.FUNCID and [funcname like concat(concat('%',{funcname}),'%')]   ) as is_parent,PFUNCID , FUNCCODE , CREATETIME from SYS_FUNC t   where 1=1 [if(isUp!=true&(isWhere!=1)) and (PFUNCID={id} )][if(isUp!=true) and [funcname like concat(concat('%',{funcname}),'%'] )][if(isUp=true) and (FUNCID={my_id} ) ] order by CREATETIME";
			SimpleCmpleSQL cmple=	new SimpleCmpleSQL(sql,null);
			
			Map map= new HashMap() ;
		        map.put("up", false);
		        map.put("parent", 1);
		        map.put("a", 1);
		        SqlAndParam sp=   cmple.getSQL(map);
		        System.out.println(sql);
		      System.out.println(sp.getSql());
		     
		
	}

}
